package com.yanqu.road.server.agent;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.enums.eAgentErrorCode;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.agent.inter.AgentReload;
import com.yanqu.road.utils.classutil.ClassHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Set;

public class AgentInterfaceMgr extends TempMgr {
    private static final Logger log = LogManager.getLogger(AgentInterfaceMgr.class.getName());
    private static final HashMap<String, Object> classMap = new HashMap<>();

    private static Object getClassByName(String className) {
        return classMap.get(className);
    }

    /**
     * 获取默认的返回值Json格式
     */
    public static JSONObject getDefaultRet() {
        JSONObject resultObj = new JSONObject();
        resultObj.put("status", 0);
        resultObj.put("msg", "操作失败!");
        return resultObj;
    }

    public static void setCommonRet(JSONObject ret, int type) {
        if (type == eAgentErrorCode.Success.getValue()) {
            ret.put("status", 1);
            ret.put("msg", "操作成功！");
        } else if (type == eAgentErrorCode.ArgumentError.getValue()) {
            ret.put("msg", "传入参数错误，操作失败！");
        } else if (type == eAgentErrorCode.DataSaveError.getValue()) {
            ret.put("msg", "保存数据失败，操作失败！");
        } else if (type == eAgentErrorCode.ErrorPlayer.getValue()) {
            ret.put("msg", "找不到玩家，操作失败！");
        } else if (type == eAgentErrorCode.FunException.getValue()) {
            ret.put("msg", "服务器逻辑异常，操作失败！");
        } else if (type == eAgentErrorCode.GetDataError.getValue()) {
            ret.put("msg", "获取数据库数据异常，操作失败！");
        } else if (type == eAgentErrorCode.PlayerOffline.getValue()) {
            ret.put("msg", "玩家不在线，操作失败！");
        }

    }

    public static String executeAgentInterface(String op, String param) {
        JSONObject resultObj = new JSONObject();
        resultObj.put("status", "0");
        try {
            String opArr[] = op.split("\\|");
            if (opArr.length != 2) {
                log.error("AgentInterfaceMgr executeAgentInterface Argument Error! op:" + op);
                resultObj.put("msg", "参数Op个数错误，op:" + op);
                return resultObj.toString();
            }
            String className = opArr[0];
            String funName = opArr[1];
            if (StringUtils.isNullOrEmpty(className) || StringUtils.isNullOrEmpty(funName)) {
                log.error("AgentInterfaceMgr executeAgentInterface Argument Is NULL OR Empty! op:" + op);
                resultObj.put("msg", "参数OP错误，没有找到className或者Fun==>op:" + op);
                return resultObj.toString();
            }
            // 转成JSON函数里面直接取值
            JSONObject dataObj;
            try {
                dataObj = JSONObject.parseObject(param);
            } catch (Exception e) {
                resultObj.put("msg", "json格式出错！===> json 字符串为:" + param);
                return resultObj.toString();
            }
            Object classObj = getClassByName(className);
            if (null != classObj) {
                Method method = classObj.getClass().getMethod(funName, JSONObject.class);
                if (null != method) {
                    return (String) method.invoke(classObj, dataObj);
                } else {
                    log.error("AgentInterfaceMgr executeAgentInterface can't find Fun Error! op:" + op);
                }
            } else {
                log.error("AgentInterfaceMgr executeAgentInterface can't find Class Error! op:" + op);
            }
        } catch (Exception e) {
            log.error("AgentInterfaceMgr executeAgentInterface E:", e);
            e.printStackTrace();
            log.error("executeAgentInterface 没有找到对应的OP下的类或者类下的方法错误！===>OP:" + op);
        }
        resultObj.put("msg", "没有找到对应的OP下的类或者类下的方法错误！===>OP:" + op);
        return resultObj.toString();
    }

    @Override
    public boolean reload() {
        Package pack = AgentReload.class.getPackage();
        Set<Class<?>> classSet = ClassHelper.getClasses(pack);
        log.info("AgentInterfaceMgr Load Class Success.classMap size():{}", classSet.size());
        for (Class<?> data : classSet) {
            processClass(data);
        }
        return true;
    }

    private void processClass(Class<?> data) {
        String className = data.getSimpleName();
        if (classMap.containsKey(className)) {
            log.error("AgentInterfaceMgr Error! Same ClassName In AgentInterface!!! ClassName: {}" , data.getName());
            return;
        }
        try {
            classMap.put(className, data.newInstance());
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean init() {
        return reload();
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean save() {
        return false;
    }
}
